package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.User;
import com.example.forum.services.IUserServices;
import com.example.forum.utils.MD5Utils;
import com.example.forum.utils.UUIDSaltUtils;
import com.sun.istack.internal.NotNull;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


//在httpBody里面返回的是数据
@Api(tags = "用户接口")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserServices userServices;

    /**
     * date: 2024/09/08 10:22<br/>
     * Description:
     * 用户注册
     *
     * @author: jmy <br/>
     */
    @ApiOperation("用户注册")
    @PostMapping("/register")
    //@RequestParam 指定url中的的参数
    public AppResult register(@ApiParam("用户名") @RequestParam("userName") @NotNull String userName,
                              @ApiParam("用户昵称") @RequestParam("nickName") @NotNull String nickName,
                              @ApiParam("用户密码") @RequestParam("password") @NotNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NotNull String passwordRepeat) {

        log.info("/user/register 接收参数: userName: " + userName + " password:" + password + "nickName:" + nickName + "passwordRepeat:" + passwordRepeat);

        if (!password.equals(passwordRepeat)) {
            log.error(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //对密码进行加密
        String salt = UUIDSaltUtils.uuidSalt_32();
        String saltPassword = MD5Utils.md5Salt(password, salt);

        //用户信息存入数据库
        User user = new User(userName, nickName, saltPassword, salt);
        boolean result = userServices.createNormalUser(user);
        if (result) {
            return AppResult.success(ResultCode.SUCCESS);
        }
        return AppResult.failed();
    }

    /**
     * date: 2024/09/08 23:19<br/>
     * Description: 用户登录
     *
     * @author: jmy <br/>
     */
    @ApiOperation("用户登录接口")
    @PostMapping("/login")
    public AppResult login(@ApiParam("用户名") @RequestParam("userName") @NotNull String userName
            , @ApiParam("用户密码") @RequestParam("password") @NotNull String password
            , HttpServletRequest request) {
        log.info("user/login 接收参数: userName" + userName + "password" + password);
        //1.校验用户是否存在
        User user = userServices.selectByUserName(userName);
        System.out.println("登录用户信息" + user);
        if (user == null) {
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        User result = userServices.login(userName, password);
        if (result != null) {
            //2.如果登录成功，就把User 对象设置到Session 作用域中
            HttpSession session = request.getSession(true);

            session.setAttribute(AppConfig.USER_SESSION, user);
            return AppResult.success(result);
        }
        return AppResult.failed(ResultCode.FAILED);
    }

    /**
     * date: 2024/09/09 17:12<br/>
     * Description: 通过id查询用户信息
     *
     * @author: jmy <br/>
     */
    @ApiOperation("通过id查询用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfoById(HttpServletRequest request, @ApiParam("用户id") @RequestParam(value = "id", required = false) Long id) {
        log.info("user/info 接收参数: id: " + id);

        // 1.如果id为空，从session种获取信息
        if (id == null) {
            //如果没有session 不创建
            HttpSession session = request.getSession(false);
            if (session == null || session.getAttribute(AppConfig.USER_SESSION) == null) {
                log.info(ResultCode.FAILED_USER_NOT_EXISTS.toString());
                return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
            }
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            User userInfo = userServices.selectById(user.getId());
            return AppResult.success(userInfo);
        }
        //用户传如非空id 直接根据id查询用户信息
        User user = userServices.selectById(id);
        if (user == null) {
            log.warn("用户不存在，接收参数: id: " + id);
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }

    /**
     * date: 2024/09/10 14:59<br/>
     * Description: 用户退出登录
     *
     * @author: jmy <br/>
     */
    @ApiOperation("用户退出登录")
    @GetMapping("/logOut")
    public AppResult logOut(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        //
        if (session != null) {
            //表示用户在登录状态，直接消除session
            session.invalidate();
            //消除token

        }
        return AppResult.success("您已退出登录");
    }

    /**
     * date: 2024/09/17 21:25<br/>
     * Description: 修改用户信息
     *
     * @author: jmy <br/>
     */
    @ApiOperation("用户修改个人信息")
    @PostMapping("/modifyInfo")

    // @ApiParam("用户名") @RequestParam(value = "username" ,required = false)String username,
    //  @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender,
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("昵称") @RequestParam(value = "nickname", required = false) String nickname,
                            @ApiParam("邮箱") @RequestParam(value = "email", required = false) String email,
                            @ApiParam("电话号码") @RequestParam(value = "phoneNum", required = false) String phoneNum,
                            @ApiParam("个人简介") @RequestParam(value = "remark", required = false) String remark) {
        log.info("user/modifyInfo" + "接收参数" +
                " nickname: " + nickname +
                " email:" + email +
                " phoneNum:" + phoneNum +
                " remark:" + remark);

        User user = (User) request.getSession().getAttribute(AppConfig.USER_SESSION);
        //全非空校验
        if (nickname == null &&
                email == null &&
                phoneNum == null &&
                remark == null) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        //封装对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setNickName(nickname);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);

        log.info("改动信息: " + updateUser);
        //调用service
        userServices.modifyInfo(updateUser);

        //在数据库中查 最新的信息 返回更新后的值
        user = userServices.selectById(user.getId());

        //把更新后的用户信息 重新存入session
        request.getSession().setAttribute(AppConfig.USER_SESSION, user);
        //返回结果
        return AppResult.success(user);
    }

    /**
     * date: 2024/09/18 21:43<br/>
     * Description: 修改密码
     *
     * @author: jmy <br/>
     */
    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("旧密码") @NotNull @RequestParam("oldPassword") String oldPassword,
                                    @ApiParam("新密码") @NotNull @RequestParam("newPassword") String newPassword,
                                    @ApiParam("确认密码") @NotNull @RequestParam("passwordRepeat") String passwordRepeat) {
        log.info("user/modifyPwd 接收参数 : oldPassword:" + oldPassword + "   newPassword:" + newPassword + "   passwordRepeat:" + passwordRepeat);
        //1.校验密码是否为六位数字+打印日志
        if (!User.isNumeric(oldPassword) ||
                !User.isNumeric(newPassword) ||
                !User.isNumeric(passwordRepeat)) {
            log.warn(ResultCode.FAILED_PASSWORD_NOT_NUM.toString());
            return AppResult.failed(ResultCode.FAILED_PASSWORD_NOT_NUM);
        }
        //2.校验两次密码是否相等
        if (!newPassword.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //3.获取用户信息
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);

        //4.调用services修改密码
        Integer result = userServices.modifyPassword(user.getId(), newPassword, oldPassword);

        //5.判断跟新是否成功
        if (result != 1) {
            log.warn(ResultCode.FAILED.toString());
            return AppResult.failed(ResultCode.FAILED);
        }
        //6.销毁session
        if (request.getSession() != null) {
            request.getSession().invalidate();
        }
        return AppResult.success(result);
    }

}
